<!--
 * @Author: Mr · Lei
 * @Date: 2024-11-19 14:55:05
 * @LastEditors: OBKoro1
 * @LastEditTime: 2024-11-19 14:55:06
 * @FilePath: \ruituan-tuan-Agent\src\views\shop\shop_list\index.vue
 * @Description: 
 * 
 * Copyright (c) 2024 by 四川开局红科技有限公司, All Rights Reserved. 
-->
<template>
  <a-card  class="general-card">
    <a-row>
      <a-col :span="6">
        <a-space>
          <a-avatar
            :size="54"
            class="col-avatar"
            style="background-color: #ffffff"
          >
            <img
              alt="avatar"
              src="http://rtt.scwfkj.cn/images/uploads/202412181923031123.png"
            />
          </a-avatar>
          <a-statistic
            :title="$t('order.statistic.all')"
            :value="incomeInfo.all_money"
            :value-from="0"
            :precision="4"
            animation
            show-group-separator
          >
            <template #suffix>
              <span class="unit">{{ $t('order.statistic.unit') }}</span>
            </template>
          </a-statistic>
        </a-space>
      </a-col>
      <a-col :span="6">
        <a-space>
          <a-avatar :size="54" class="col-avatar">
            <img
              alt="avatar"
              src="http://rtt.scwfkj.cn/images/uploads/202412181843308586.png"
            />
          </a-avatar>
          <a-statistic
            :title="$t('order.statistic.today')"
            :value="incomeInfo.all_today_money"
            :value-from="0"
            :precision="4"
            animation
            show-group-separator
          >
            <template #suffix>
              <span class="unit">{{ $t('order.statistic.unit') }}</span>
            </template>
          </a-statistic>
        </a-space>
      </a-col>
    </a-row>
  </a-card>
  <a-card
    class="general-card"
    :title="$t('order.select')"
  >
    <a-row>
      <a-col :flex="1">
        <a-form
          :model="formModel"
          :label-col-props="{ span: 6 }"
          :wrapper-col-props="{ span: 16 }"
          label-align="left"
        >
          <a-row :gutter="16">
            <a-col :span="6">
              <a-form-item field="order_no" :label="$t('order.form.orderNo')">
                <a-input
                  v-model="formModel.order_no"
                  :placeholder="$t('order.form.orderNo.placeholder')"
                />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item
                field="shop_name"
                :label="$t('order.form.shop.name')"
              >
                <a-input
                  v-model="formModel.shop_name"
                  :placeholder="$t('order.form.shop.name.placeholder')"
                />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item field="nickname" :label="$t('order.form.nickname')">
                <a-input
                  v-model="formModel.nickname"
                  :placeholder="$t('order.form.nickname.placeholder')"
                />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item field="line_num" :label="$t('order.form.line_num')">
                <a-input
                  v-model="formModel.line_num"
                  :placeholder="$t('order.form.line_num.placeholder')"
                />
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="16">
            <a-col :span="6">
              <a-form-item field="is_line" :label="$t('order.form.is_line')">
                <a-select
                  v-model="formModel.is_line"
                  :placeholder="$t('order.form.is_line.placeholder')"
                >
                  <a-option
                    v-for="item of islineList"
                    :key="item.value"
                    :value="item.value"
                    :label="item.label"
                  />
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item field="status" :label="$t('order.form.status')">
                <a-select
                  v-model="formModel.status"
                  :placeholder="$t('order.form.status.placeholder')"
                >
                  <a-option
                    v-for="item of lineStatus"
                    :key="item.value"
                    :value="item.value"
                    :label="item.label"
                  />
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item
                field="scan_type"
                :label="$t('order.form.scan_type')"
              >
                <a-select
                  v-model="formModel.scan_type"
                  :placeholder="$t('order.form.scan_type.placeholder')"
                >
                  <a-option
                    v-for="item of scanTypeList"
                    :key="item.value"
                    :value="item.value"
                    :label="item.label"
                  />
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </a-col>
      <a-divider style="height: 84px" direction="vertical" />
      <a-col :flex="'86px'" style="text-align: right">
        <a-space direction="vertical" :size="18">
          <a-button type="primary" @click="search">
            <template #icon>
              <icon-search />
            </template>
            {{ $t('order.form.search') }}
          </a-button>
          <a-button @click="reset">
            <template #icon>
              <icon-refresh />
            </template>
            {{ $t('order.form.reset') }}
          </a-button>
        </a-space>
      </a-col>
    </a-row>
    
    <a-divider style="margin-top: 10px" />
    <a-row style="margin-bottom: 16px">
      <a-col :span="12">
        <a-space>
          <!-- <a-button type="primary" size="large">
              {{ $t('order.table.create') }}
            </a-button> -->
          {{ $t('order.table.title') }}
        </a-space>
      </a-col>
      <a-col
        :span="12"
        style="display: flex; align-items: center; justify-content: end"
      >
        <a-tooltip :content="$t('order.actions.refresh')">
          <div class="action-icon" @click="search"
            ><icon-refresh size="18"
          /></div>
        </a-tooltip>
        <a-dropdown @select="handleSelectDensity">
          <a-tooltip :content="$t('order.actions.density')">
            <div class="action-icon"><icon-line-height size="18" /></div>
          </a-tooltip>
          <template #content>
            <a-doption
              v-for="item in densityList"
              :key="item.value"
              :value="item.value"
              :class="{ active: item.value === size }"
            >
              <span>{{ item.name }}</span>
            </a-doption>
          </template>
        </a-dropdown>
        <a-tooltip :content="$t('order.actions.columnSetting')">
          <a-popover
            trigger="click"
            position="bl"
            @popup-visible-change="popupVisibleChange"
          >
            <div class="action-icon"><icon-settings size="18" /></div>
            <template #content>
              <div id="tableSetting">
                <div
                  v-for="(item, index) in showColumns"
                  :key="item.dataIndex"
                  class="setting"
                >
                  <div style="margin-right: 4px; cursor: move">
                    <icon-drag-arrow />
                  </div>
                  <div>
                    <a-checkbox
                      v-model="item.checked"
                      @change="
                        handleChange($event, item as TableColumnData, index)
                      "
                    >
                    </a-checkbox>
                  </div>
                  <div class="title">
                    {{ item.title === '#' ? '序列号' : item.title }}
                  </div>
                </div>
              </div>
            </template>
          </a-popover>
        </a-tooltip>
      </a-col>
    </a-row>
    <a-table
      row-key="id"
      column-resizable
      :loading="loading"
      :pagination="pagination"
      :columns="(cloneColumns as TableColumnData[])"
      :scroll="{ x: 1800, y: 2000 }"
      :data="orderList"
      :bordered="{ wrapper: true, cell: true }"
      :size="size"
      @page-change="onPageChange"
    >
      <template #index="{ rowIndex }">
        {{ rowIndex + 1 + (pagination.page - 1) * pagination.limit }}
      </template>
      <template #status="{ record }">
        <a-space>
          <a-tag :color="record.status === 1 ? '#ff7d00' : '#00b42a'">{{
            record.status === 1 ? '排队中' : '已完成'
          }}</a-tag>
        </a-space>
      </template>
      <template #scan_type="{ record }">
        <a-space>
          <a-tag
            :color="
              record.scan_type === 1
                ? '#00b42a'
                : record.scan_type === 2
                ? '#165dff'
                : record.scan_type === 3
                ? '#ff7d00'
                : record.scan_type === 4
                ? '#0fc6c2'
                : '#000000'
            "
          >
            {{
              record.scan_type === 1
                ? '微信扫码'
                : record.scan_type === 2
                ? '小程序扫码'
                : record.scan_type === 3
                ? '碰一碰'
                : record.scan_type === 4
                ? '首页进入'
                : '--'
            }}
          </a-tag>
        </a-space>
      </template>
      <template #line_num="{ record }">
        <a-space>
          <a-tag
            :color="
              record.line_num === 0
                ? 'black'
                : record.line_num === 1
                ? '#ff5722'
                : record.line_num === 2
                ? '#0fc6c2'
                : record.line_num === 3
                ? '#ffb400'
                : '#86909c'
            "
          >
            {{ record.line_num }}
          </a-tag>
        </a-space>
      </template>
      <template #is_line="{ record }">
        <a-space>
          <a-tag :color="record.is_line === 1 ? '#165dff' : '#86909c'">{{
            record.is_line === 1 ? '是' : '否'
          }}</a-tag>
        </a-space>
      </template>
    </a-table>
  </a-card>
</template>

<script lang="ts" setup>
  import { computed, ref, reactive, watch, nextTick, defineProps } from 'vue';
  import { useI18n } from 'vue-i18n';
  import useLoading from '@/hooks/loading';
  import { GetOrderListApi,GetOrderIncomeApi, PolicyRecord } from '@/api/order';
  import { Pagination } from '@/types/global';
  import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
  import cloneDeep from 'lodash/cloneDeep';
  import Sortable from 'sortablejs';

  type SizeProps = 'mini' | 'small' | 'medium' | 'large';
  type Column = TableColumnData & { checked?: true };

  const { loading, setLoading } = useLoading(true);
  const { t } = useI18n();
  const props = defineProps({
    type: {
      type: Number,
      default: 1,
    },
  });
  const formModel = reactive({
    type: props.type,
    order_no: '',
    is_line: '', // 1 是 2 否
    status: '',
    line_num: '',
    shop_name: '',
    nickname: '',
    scan_type: '',
  });

  const orderList = ref<PolicyRecord[]>([]);
  const cloneColumns = ref<Column[]>([]);
  const showColumns = ref<Column[]>([]);

  const size = ref<SizeProps>('medium');

  // 排队状态
  const lineStatus = [
    {
      value: '',
      label: t('order.form.status.all'),
    },
    {
      value: 1,
      label: t('order.form.status.loading'),
    },
    {
      value: 2,
      label: t('order.form.status.waiting'),
    },
  ];
  // 是否排队
  const islineList = [
    {
      value: '',
      label: t('order.form.is_line.all'),
    },
    {
      value: 1,
      label: t('order.form.is_line.yes'),
    },
    {
      value: 2,
      label: t('order.form.is_line.no'),
    },
  ];
  // 下单方式
  const scanTypeList = [
    {
      value: '',
      label: t('order.form.scan_type.all'),
    },
    {
      value: 1,
      label: t('order.form.scan_type.WeChat'),
    },
    {
      value: 2,
      label: t('order.form.scan_type.WeChatMp'),
    },
    {
      value: 3,
      label: t('order.form.scan_type.nfc'),
    },
    {
      value: 4,
      label: t('order.form.scan_type.home'),
    },
  ];
  // 分页属性
  const basePagination: Pagination = {
    page: 1,
    limit: 10,
  };
  const pagination = reactive({
    ...basePagination,
  });
  // 定义尺寸
  const densityList = computed(() => [
    {
      name: t('order.size.mini'),
      value: 'mini',
    },
    {
      name: t('order.size.small'),
      value: 'small',
    },
    {
      name: t('order.size.medium'),
      value: 'medium',
    },
    {
      name: t('order.size.large'),
      value: 'large',
    },
  ]);
  // 查询结果 每列标题与字段
  const columns = computed<TableColumnData[]>(() => [
    {
      title: t('order.columns.index'),
      dataIndex: 'index',
      slotName: 'index',
      width: 50,
      align: 'center',
    },
    {
      title: t('order.columns.orderNo'),
      dataIndex: 'order_no',
      width: 200,

      align: 'center',
    },
    {
      title: t('order.columns.shopName'),
      dataIndex: 'shop.name',
      align: 'center',
      width: 250,
    },
    {
      title: t('order.columns.shopPhone'),
      dataIndex: 'shop.mobile',
      align: 'center',
      width: 150,
    },
    {
      title: t('order.columns.scan_type'),
      dataIndex: 'scan_type',
      slotName: 'scan_type',
      align: 'center',
      width: 150,
    },
    {
      title: t('order.columns.pay_money'),
      dataIndex: 'pay_money',
      align: 'center',
      width: 150,
    },
    {
      title: t('order.columns.status'),
      dataIndex: 'status',
      align: 'center',
      slotName: 'status',
      width: 100,
    },
    {
      title: t('order.columns.line_num'),
      dataIndex: 'line_num',
      align: 'center',
      slotName: 'line_num',
      width: 100,
    },

    {
      title: t('order.columns.is_line'),
      dataIndex: 'is_line',
      align: 'center',
      slotName: 'is_line',
      width: 100,
    },
    {
      title: t('order.columns.userName'),
      dataIndex: 'user.nickname',
      align: 'center',
      width: 150,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: t('order.columns.userPhone'),
      dataIndex: 'user.mobile',
      align: 'center',
      width: 150,
    },
    {
      title: t('order.columns.createtime'),
      dataIndex: 'createtime',
      align: 'center',
    },
  ]);

  // 查询/筛选 列表
  const fetchData = async () => {
    const params = {
      ...basePagination,
      ...formModel,
    };
    setLoading(true);
    try {
      const { data } = await GetOrderListApi(params);
      orderList.value = data.data;
      pagination.page = params.page;
      pagination.total = data.total;
    } catch (err) {
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  };

  const search = () => {
    fetchData();
  };
  search();
  const onPageChange = (page: number) => {
    basePagination.page = page;
    fetchData();
  };
  const reset = () => {
    formModel.type = 2;
    formModel.order_no = '';
    formModel.is_line = ''; // 1 是 2 否
    formModel.status = '';
    formModel.line_num = '';
    formModel.shop_name = '';
    formModel.nickname = '';
    basePagination.page = 1;
    fetchData();
  };
  const incomeInfo = ref({
    all_money: 0,
    all_today_money: 0,
  });
  const getIncome = async () => {
    setLoading(true);
    try {
      const { data } = await GetOrderIncomeApi({ type: props.type });
      incomeInfo.value = data;
    } catch (err) {
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  };
  getIncome();
  const handleSelectDensity = (
    val: string | number | Record<string, any> | undefined,
    e: Event
  ) => {
    size.value = val as SizeProps;
  };

  const handleChange = (
    checked: boolean | (string | boolean | number)[],
    column: Column,
    index: number
  ) => {
    if (!checked) {
      cloneColumns.value = showColumns.value.filter(
        (item) => item.dataIndex !== column.dataIndex
      );
    } else {
      cloneColumns.value.splice(index, 0, column);
    }
  };

  const exchangeArray = <T extends Array<any>>(
    array: T,
    beforeIdx: number,
    newIdx: number,
    isDeep = false
  ): T => {
    const newArray = isDeep ? cloneDeep(array) : array;
    if (beforeIdx > -1 && newIdx > -1) {
      // 先替换后面的，然后拿到替换的结果替换前面的
      newArray.splice(
        beforeIdx,
        1,
        newArray.splice(newIdx, 1, newArray[beforeIdx]).pop()
      );
    }
    return newArray;
  };

  const popupVisibleChange = (val: boolean) => {
    if (val) {
      nextTick(() => {
        const el = document.getElementById('tableSetting') as HTMLElement;
        const sortable = new Sortable(el, {
          onEnd(e: any) {
            const { oldIndex, newIndex } = e;
            exchangeArray(cloneColumns.value, oldIndex, newIndex);
            exchangeArray(showColumns.value, oldIndex, newIndex);
          },
        });
      });
    }
  };

  watch(
    () => columns.value,
    (val) => {
      cloneColumns.value = cloneDeep(val);
      cloneColumns.value.forEach((item, index) => {
        item.checked = true;
      });
      showColumns.value = cloneDeep(cloneColumns.value);
    },
    { deep: true, immediate: true }
  );
</script>

<script lang="ts">
  export default {
    name: 'List',
  };
</script>

<style scoped lang="less">
  .container {
    padding: 0 20px 20px 20px;
  }

  :deep(.arco-table-th) {
    &:last-child {
      .arco-table-th-item-title {
        margin-left: 16px;
      }
    }
  }

  .action-icon {
    margin-left: 12px;
    cursor: pointer;
  }

  .active {
    color: #0960bd;
    background-color: #e3f4fc;
  }

  .setting {
    display: flex;
    align-items: center;
    width: 200px;

    .title {
      margin-left: 12px;
      cursor: pointer;
    }
  }
</style>
